var app = getApp();
var util = require('../../utils/util.js');
var common = require('../../utils/common.js');
var PageBase = require('../../common/PageBase.js');
var ajax = require('../../utils/ajax.js');

Page(common.extendPage(PageBase, {
  data: {
    dataLoaded: false,
    couponList: [],
    hasMobile: 0
  },

  onLoad(options) {
    var _self = this;
    common.initApp({
      loginSuc: () => {
        if (app.getUInfo().mobile != '') {
          //debugger;
          _self.setData({
            hasMobile: 1
          })
        }
        _self._getList();
      }
    });

  },

  onPullDownRefresh() {

  },

  onReachBottom() {

  },

  //授权微信绑定手机号
  _getmobile(evt) {
    //debugger;

    var {
      errMsg,
      iv,
      encryptedData
    } = evt.detail;

    if (!/:ok$/.test(errMsg)) {
      if (errMsg == 'getPhoneNumber:fail user deny') {
        var text = "为了您更好的购物体验，请您同意授权后再领取优惠券"
        util.alert(text, function () {
          return false;
        })
      } else {
        util.alert(errMsg);
      }
      return;
    }
    else {

      this.setData({
        hasMobile: 1
      })

      ajax.P({
        url: 'm=user&c=index&a=mobile',
        data: {
          iv,
          code: encryptedData,
          uid: app.getUid()
        },
        success: (data) => {
          console.log(data,'EEEEEEEEEEE');
          app.setMobile(data.data.mobile)
        },
        fail: (data) => {
        }
      });

      this._getCoupon(evt);


    }

  },

	/**
	 * 获取优惠券列表
	 * @return {[type]} [description]
	 */
  _getList() {
    ajax.G({
      url: "m=plugins&c=redpackets",
      data: {
        uid: app.getUid()
      },
      success: (res) => {
        //debugger;
        var couponList = res.data.coupons;
        this.setData({
          dataLoaded: true,
          couponList: couponList
        });
      }
    });
  },

  _getCoupon(evt) {
    //debugger;
    var couponid = evt.currentTarget.dataset.id;
    ajax.P({
      url: "m=plugins&c=coupon&a=send",
      data: {
        uid: app.getUid(),
        couponid: couponid
      },
      success: (res) => {
        //debugger;
        if(res.code == 1){
          util.showWarn(res.msg);
          return;
        }
        var couponList = res.data.item;
        wx.showToast({
          title: '领取成功',
        })
      },
      fail: (res) => {
        //debugger;
        wx.showToast({
          title: res.msg
        })
      }
    });

  }

}));